using System;
using System.Collections;
using System.Globalization;
using System.Text;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Common;
using Sedna.Core.Controller.Configurations;
using Sedna.DAO;

namespace Sedna.Core.Controls.Actions
{
    public abstract class IndexedEntityGridAction : AbstractAction
    {
        private const string ROW_NUM = "index";

        private String gridDataPath;
        private IDataGridCommandArgumentsParser commandArgumentsParser;
        private IBaseDAO objectDAO;
        private bool autoSessionAttach = true;

        # region Properties

        public string GridDataPath
        {            
            set { gridDataPath = value; }
        }

        public IDataGridCommandArgumentsParser CommandArgumentsParser
        {
            set { commandArgumentsParser = value; }
        }

        public IBaseDAO ObjectDAO
        {
            set { objectDAO = value; }
        }

        public bool AutoSessionAttach
        {
            set { autoSessionAttach = value; }
        }

        public IList GridData
        {
            get { return scopePathParser.Parse(gridDataPath).Value as IList; }
        }

        # endregion

        protected Object GetSelectedEntity(IExecutionContext executionContext)
        {
            Object entity = GridData[GetSelectedRowIndex(executionContext)];
            
            if (autoSessionAttach)
            {
                objectDAO.AttachToSession(entity);
            }

            return entity;
        }

        protected int GetSelectedRowIndex(IExecutionContext executionContext)
        {
            IDictionary commandArguments = commandArgumentsParser.ParseCommandArguments(executionContext.CommandArgument);

            return Convert.ToInt32(commandArguments[ROW_NUM], CultureInfo.InvariantCulture);
        }

    }
}
